//
//  BLSendMomentController.m
//  Byelone
//
//  Created by Qi Liu on 2021/2/21.
//

#import "BLSendMomentController.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"
#import "BLGridViewFlowLayout.h"
#import "BLPhotosCell.h"
#import "BLPhotosFootView.h"
#import "BLMeetAlert.h"
#import <FLAnimatedImage/FLAnimatedImageView.h>
#import <FLAnimatedImage/FLAnimatedImage.h>
//#import "FLAnimatedImage.h"

#define Max_Image_Width 1080
#define Max_Image_Height 1920

@interface BLSendMomentController ()<UITextViewDelegate,UICollectionViewDelegate,
UICollectionViewDataSource,UIGestureRecognizerDelegate,
TZImagePickerControllerDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate>{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    CGFloat _itemWH;
    CGFloat _margin;
}
@property (weak, nonatomic) IBOutlet UILabel *plaabel;
@property (weak, nonatomic) IBOutlet UITextView *contentTextView;
@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *itemCollectionView;
@property (strong, nonatomic) BLGridViewFlowLayout *layout;
@property (nonatomic,strong) BLPhotosFootView * sectionView;
@property (strong, nonatomic)  UIView *baseView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property(nonatomic,assign)NSInteger maxSelected;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewTop;
@property (nonatomic,strong) NSMutableArray * modelArray;
@property (nonatomic,strong) NSMutableArray * urlArray;
@end

@implementation BLSendMomentController

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发布动态";
    
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    _urlArray = [NSMutableArray array];
    _modelArray = [NSMutableArray array];
    
    if (_sendType == BLComment_Type_Text) {
        self.leftLabel.hidden = YES;
        self.rightLabel.hidden = YES;
        self.lineView.hidden = YES;
        self.collectionViewTop.constant = 20;
    }else if (_sendType == BLComment_Type_Text_Pic){
        self.leftLabel.text = @"上传图片";
        self.rightLabel.text = @"(最多可以上传9张)";
        _maxSelected = 9;
    }else if (_sendType == BLComment_Type_Text_Video){
        self.leftLabel.text = @"上传视频";
        self.rightLabel.text = @"(最多可以上传一个视频,且大小低于10m)";
        _maxSelected = 1;
    }
    
    [self configUI];
}

-(void)configUI{
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[BLGridViewFlowLayout alloc] init];
    _itemCollectionView.collectionViewLayout = _layout;
    
    CGFloat rgb = 244 / 255.0;
    _itemCollectionView.alwaysBounceVertical = YES;
    _itemCollectionView.delegate = self;
    _itemCollectionView.dataSource = self;
    _itemCollectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _itemCollectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _itemCollectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_itemCollectionView registerClass:[BLPhotosCell class] forCellWithReuseIdentifier:@"BLPhotosCell"];
    [_itemCollectionView registerNib:[UINib nibWithNibName:@"BLPhotosFootView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"BLPhotosFootView"];
    _itemCollectionView.backgroundColor = [UIColor clearColor];
    [_itemCollectionView reloadData];
    _contentTextView.backgroundColor = [UIColor chColorWithHexString:@"#F0F2F5"];
    _contentTextView.layer.cornerRadius = 5;
    _contentTextView.layer.masksToBounds = YES;
    _contentTextView.delegate = self;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboard:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:self.itemCollectionView]) {
        return NO;
    }
    return YES;
}


- (void)hideKeyboard:(UITapGestureRecognizer *)tap{
    
    [_contentTextView resignFirstResponder];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSInteger contentSizeH = 14 * 35 + 20;
    _margin = 4;
    _itemWH = ((self.view.tz_width -34) - 2 * _margin - 4) / 3 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    [self.itemCollectionView setCollectionViewLayout:_layout];
    
}

#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (_sendType == BLComment_Type_Text) {
        return 0;
    }
    
    if (_selectedPhotos.count >= self.maxSelected) {
        return _selectedPhotos.count;
    }
    return _selectedPhotos.count + 1;
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(12, 0, 20, 0);
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width, 40);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    BLPhotosFootView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :UICollectionElementKindSectionFooter   withReuseIdentifier:@"BLPhotosFootView"   forIndexPath:indexPath];
    [view.saveBtn setTitle:@"发布" forState:UIControlStateNormal];
    [view.saveBtn addTarget:self action:@selector(photoSave:) forControlEvents:UIControlEventTouchUpInside];
    view.isFoot = YES;
    return view;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BLPhotosCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BLPhotosCell" forIndexPath:indexPath];
    //    cell.videoImageView.hidden = YES;
    if (indexPath.item == _selectedPhotos.count) {
        cell.imageView.hidden = YES;
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.hidden = NO;
        cell.imageView.image = _selectedPhotos[indexPath.item];
        cell.asset = _selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.gifLable.hidden = YES;
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
        [self pushTZImagePickerController];
    }else{
        
        PHAsset *asset = _selectedAssets[indexPath.item];
        BOOL isVideo = NO;
        isVideo = asset.mediaType == PHAssetMediaTypeVideo;
        if ([[asset valueForKey:@"filename"] containsString:@"GIF"] && _sendType == BLComment_Type_Text_Pic) {
            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else if (isVideo && _sendType == BLComment_Type_Text_Video) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.item];
            imagePickerVc.maxImagesCount = 9;
            imagePickerVc.allowPickingGif = YES;
            imagePickerVc.allowPickingOriginalPhoto = YES;
            imagePickerVc.allowPickingMultipleVideo = YES;
            imagePickerVc.showSelectedIndex = YES;
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                self->_selectedPhotos = [NSMutableArray arrayWithArray:photos];
                self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
                self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
                [self->_itemCollectionView reloadData];
                self->_itemCollectionView.contentSize = CGSizeMake(0, ((self->_selectedPhotos.count + 2) / 3 ) * (self->_margin + self->_itemWH));
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}
#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    if (self.maxSelected <= 0) {
        return;
    }
    BOOL isVideo = (_sendType == BLComment_Type_Text_Video);
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxSelected columnNumber:4 delegate:self pushPhotoPickerVc:YES];
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    if (self.maxSelected > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = isVideo;
    imagePickerVc.allowPickingImage = !isVideo;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.allowPickingMultipleVideo = !isVideo; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;//允许剪裁
    imagePickerVc.needCircleCrop = NO;//圆形剪裁
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = self.view.tz_width - 2 * left;
    NSInteger top = (self.view.tz_height - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
    // 自定义gif播放方案
    [[TZImagePickerConfig sharedInstance] setGifImagePlayBlock:^(TZPhotoPreviewView *view, UIImageView *imageView, NSData *gifData, NSDictionary *info) {
        FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:gifData];
        FLAnimatedImageView *animatedImageView;
        for (UIView *subview in imageView.subviews) {
            if ([subview isKindOfClass:[FLAnimatedImageView class]]) {
                animatedImageView = (FLAnimatedImageView *)subview;
                animatedImageView.frame = imageView.bounds;
                animatedImageView.animatedImage = nil;
            }
        }
        if (!animatedImageView) {
            animatedImageView = [[FLAnimatedImageView alloc] initWithFrame:imageView.bounds];
            animatedImageView.runLoopMode = NSDefaultRunLoopMode;
            [imageView addSubview:animatedImageView];
        }
        animatedImageView.animatedImage = animatedImage;
    }];
    
#pragma mark - 到这里为止
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}


/**
 *  选择相册图片（包括gif图片）
 *
 *  @param assets PHAsset对象数组
 */
- (NSMutableArray *)selectedAlbumPhotosIncludingGifWithPHAssets:(NSArray*)assets {
    
    NSMutableArray *imageArray = [NSMutableArray array];
    CGSize targetSize = CGSizeMake(Max_Image_Width, Max_Image_Height);
    PHImageRequestOptions *options = [PHImageRequestOptions new];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.synchronous = YES;
    
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    for (BLImageModel * model in assets) {
        if (model.asset) {
            [imageManager requestImageDataForAsset:model.asset
                                           options:options
                                     resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                
                //gif 图片  暂时只处理gif
                if ([dataUTI isEqualToString:(__bridge NSString *)kUTTypeGIF]) {
                    BOOL downloadFinined = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey]);
                    if (downloadFinined && imageData) {
                        //                        BLImageModel *model = [[BLImageModel alloc] init];
                        model.imageData = imageData;
                        //                        model.image = [UIImage imageWithData:imageData];
                        model.isGif = YES;
                        [imageArray addObject:model];
                    }
                }else{
                    model.isImage = YES;
                    [imageArray addObject:model];
                }
                //                else {
                //                    //其他格式的图片，直接请求压缩后的图片
                //                    [imageManager requestImageForAsset:model.asset
                //                                            targetSize:targetSize
                //                                           contentMode:PHImageContentModeAspectFill
                //                                               options:options
                //                                         resultHandler:^(UIImage *result, NSDictionary *info) {
                //                        // 得到一张 UIImage，展示到界面上
                //                        NSNumber *isDegraded = info[PHImageResultIsDegradedKey];
                //                        if (!isDegraded.boolValue) {
                //    //                        result = [self fixImageOrientation:result];
                //                            BLImageModel *model = [BLImageModel modelWithUIImage:result];
                //                            [imageArray addObject:model];
                //                        }
                //                    }];
                //                }
                
            }];
        }
        
        
    }
    
    return imageArray;
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    [_itemCollectionView reloadData];
}
#pragma mark - TZImagePickerControllerDelegate
/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

//选择照片后的回调
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    
    NSMutableArray * modelArray = [NSMutableArray array];
    for (NSInteger i = 0; i< _selectedPhotos.count; i++) {
        BLImageModel * model = [BLImageModel new];
        model.image = [_selectedPhotos objectAtIndex:i];
        model.asset = [_selectedAssets objectAtIndex:i];
        [modelArray addObject:model];
    }
    NSArray * array = [self selectedAlbumPhotosIncludingGifWithPHAssets:modelArray];
    [self.modelArray addObjectsFromArray:array];
    
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_itemCollectionView reloadData];
    // 3. 获取原图的示例，用队列限制最大并发为1，避免内存暴增
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;
    self.sectionView.photoCount.text = [NSString stringWithFormat:@"%lu/%ld",(unsigned long)_selectedPhotos.count,(long)_maxSelected];
}


//选择视频后的回调
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
        NSData *data = [NSData dataWithContentsOfFile:outputPath];
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        
        BLImageModel * model = [BLImageModel new];
        model.videoData = data;
        model.image = coverImage;
        model.isVideo = YES;
        
        [self.modelArray addObject:model];
        
        
    } failure:^(NSString *errorMessage, NSError *error) {
        [HUD showtip:@"视频导出失败"];
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
    [_itemCollectionView reloadData];
}


-(void)sendTrends:(NSArray *)urlArray{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:@{@"content":self.contentTextView.text?:@"",@"type":@(self.sendType)}];
    
    NSMutableArray *arrayItem = [NSMutableArray new];
    for (NSDictionary *dict in urlArray) {
        NSString *str = dict[@"photoPath"];
        NSDictionary *dictItem = @{@"width":dict[@"weight"],@"height":dict[@"height"],@"momentUrl":str?:@""};
        [arrayItem addObject:dictItem];
    }
    if (arrayItem.count>0) {
        [param setValue:arrayItem forKey:@"momentUrlList"];
    }
    
    MJWeakSelf;
    [BLHttpTool postJson:BL_MOMENT_ISSUE params:param successBlock:^(NSDictionary * _Nonnull obj) {
        if (obj) {
            [[BLHUD shareHud]showtip:@"发布成功"];
            [self.navigationController popViewControllerAnimated:YES];
            if (weakSelf.sendBack) {
                weakSelf.sendBack();
            }
        }
    } failedBlock:^(NSError * _Nonnull error) {
        
    }];
}

// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(PHFetchResult *)result {
    return YES;
}
// 决定asset显示与否
- (BOOL)isAssetCanBeDisplayed:(PHAsset *)asset {
    return YES;
}
// 决定照片能否被选中
- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
    return YES;
}
- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.itemCollectionView numberOfItemsInSection:0] <= _selectedPhotos.count) {
        [_selectedPhotos removeObjectAtIndex:sender.tag];
        [_selectedAssets removeObjectAtIndex:sender.tag];
        [self.itemCollectionView reloadData];
        return;
    }
    
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [_itemCollectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self->_itemCollectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_itemCollectionView reloadData];
    }];
    self.sectionView.photoCount.text = [NSString stringWithFormat:@"%lu/%ld",(unsigned long)_selectedPhotos.count,(long)_maxSelected];
}


-(void)photoSave:(UIButton *)sender{
    
    if (self.sendType == BLComment_Type_Text_Pic) {
        if (self.modelArray.count <= 0) {
            [BLMeetAlert showSendAlertView];
            return;
        }
    }
    
    if (self.sendType == BLComment_Type_Text_Video) {
        BLImageModel * model = [_modelArray firstObject];
        if ([model.videoData length]/1000>10*1000){
            [HUD showtip:@"视频超过10M"];
            return;
            //超过10M ....
        }
        
    }
    
    [BLTool upLoadImageArray:self.modelArray type:UpLoadImageType_Moment success:^(NSArray * _Nonnull urlArray) {
        [self.urlArray addObjectsFromArray:urlArray];
        [self sendTrends:urlArray];
        
    } failure:^(NSString * _Nonnull errorString) {
        
    }];
    
    
//    NSLog(@"保存图片");
//    //    发布图文
//    if (self.sendType == BLComment_Type_Text_Pic) {
//        [self uploadImage];
//    }else if (self.sendType == BLComment_Type_Text){
//        [self sendTrends:nil];
//    }
    
}



#pragma mark - 发布相关
-(void)uploadImage{
    if (_selectedPhotos.count == 0) {
        [BLMeetAlert showSendAlertView];
        return;
    }
    
    [BLTool upLoadImageArray:_selectedPhotos type:UpLoadImageType_Moment success:^(NSArray * _Nonnull urlArray) {
        NSLog(@"上传图片的回调链接：%@",urlArray);
        [self sendTrends:urlArray];
    } failure:^(NSString * _Nonnull errorString) {
        
    }];
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    //    self.ploLabel.hidden = YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0) {
        self.plaabel.hidden = NO;
    }else{
        self.plaabel.hidden = YES;
    }
}

@end
